package org.oschina.zb.platform.localmsg.mysql.dao;

import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.oschina.zb.platform.core.base.BaseDao;
import org.oschina.zb.platform.core.mybatis.Page;
import org.oschina.zb.platform.localmsg.contants.LocalMessageConstant;
import org.oschina.zb.platform.localmsg.mq.QMessage;
import org.oschina.zb.platform.localmsg.mq.QSender;
import org.oschina.zb.platform.localmsg.mysql.entity.LocalMessage;
import org.oschina.zb.platform.localmsg.mysql.mapper.LocalMessageMapper;
import org.oschina.zb.platform.localmsg.util.JsonAdapter;
import org.springframework.stereotype.Repository;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

@Repository
public class LocalMessageDao extends BaseDao<LocalMessageMapper, LocalMessage> {

	@Resource
	private QSender qSender;

	public void insertMessage(Map<String, String> paramMap, Short messageType, String messageName) {

		// 1.保存本地消息
		LocalMessage localMessage = new LocalMessage();
		localMessage.setType(messageType);
		localMessage.setStatus(LocalMessageConstant.STATUS_UNFINISHED);
		localMessage.setParams(JsonAdapter.object2string(paramMap));
		localMessage.setCreatedAt(new Date());
		this.insert(localMessage);

		// 2.扔到消息队列
		QMessage qMessage = new QMessage();
		qMessage.setId(localMessage.getId());
		qMessage.setParams(paramMap);
		qMessage.setType(messageType);
		qSender.send(messageName, qMessage);
	}

	public Page<LocalMessage> findPageOfUnFinished(String createTime, int currentPage, int pageSize) {

		LocalMessage query = new LocalMessage();
		EntityWrapper<LocalMessage> wrapper = new EntityWrapper<LocalMessage>(query);
		if (null != createTime) {
			wrapper.le("created_at_", createTime);
		}
		Page<LocalMessage> page = new Page<>(currentPage, pageSize);
		return this.selectPage(page, wrapper);
	}

}
